package moe.server;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerResolver;

/*
 * 支持正则表达式和“*”通配符(总是匹配任何Handler)
 */
public class HttpRequestHandlerRegistry implements HttpRequestHandlerResolver {
	private Map<String, HttpRequestHandler> map;

	public HttpRequestHandlerRegistry() {
		map = new LinkedHashMap<String, HttpRequestHandler>();
	}

	public HttpRequestHandler lookup(String requestURI) {
		if (requestURI == null) {
			throw new IllegalArgumentException("Request URI may not be null");
		}
		int index = requestURI.indexOf("?");
		if (index != -1) {
			requestURI = requestURI.substring(0, index);
		}

		HttpRequestHandler result = this.map.get(requestURI);
		if (result == null) {
			for (String regex : map.keySet()) {
				if (regex.equals("*") || requestURI.matches(regex)) {
					result = map.get(regex);
					break;
				}
			}
		}
		return result;
	}

	public void register(final String pattern, final HttpRequestHandler handler) {
		if (pattern == null) {
			throw new IllegalArgumentException("URI request pattern may not be null");
		}
		if (handler == null) {
			throw new IllegalArgumentException("Request handler may not be null");
		}
		map.put(pattern, handler);
	}

	public void unregister(final String pattern) {
		map.remove(pattern);
	}
}
